<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button v-if="isAuth('disk:file:save')" type="primary" @click="uploadFile()">上传文件</el-button>
        <el-button v-if="isAuth('disk:file:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
        <el-button @click="addTab()" type="primary">新增标签</el-button>
        <el-button @click="editTab()" type="primary">管理标签</el-button>
      </el-form-item>
    </el-form>
    <el-tabs :tab-position="tabPosition" v-model="tabsLabelId" @tab-click="changeLabel">
      <el-tab-pane 
        v-for="editableTab in editableTabs" 
        :key="editableTab.labelId"
        :name="editableTab.labelId"
        :label="editableTab.labelName">
        <el-table
          :data="dataList"
          border
          v-loading="dataListLoading"
          @selection-change="selectionChangeHandle"
          style="width: 100%;">
          <el-table-column
            type="selection"
            header-align="center"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            prop="filename"
            header-align="center"
            align="center"
            label="文件名">
          </el-table-column>
          <el-table-column
            prop="length"
            header-align="center"
            align="center"
            label="文件大小"
            >
          </el-table-column>
          <el-table-column
            prop="type"
            header-align="center"
            align="center"
            label="文件类型">
          </el-table-column>
          <el-table-column
            prop="createTime"
            header-align="center"
            align="center"
            label="文件创建时间">
          </el-table-column>
          <el-table-column
            prop="updateTime"
            header-align="center"
            align="center"
            label="文件更新时间">
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="150"
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.fileId)">修改</el-button>
              <el-button type="text" size="small" @click="downloadFile(scope.row.fileId)">下载</el-button>
              <el-button type="text" size="small" @click="deleteHandle(scope.row.fileId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <!-- 上传文件 -->
    <file-upload v-if="uploadVisible" ref="fileUpload" @refreshDataList="getDataList"></file-upload>
    <!-- 新增标签 -->
    <label-add v-if="addLabelVisible" ref="labelAdd" @refreshLabelList="getLabelList"></label-add>
    <!-- 编辑标签 -->
    <label-edit v-if="editLabelVisible" ref="labelEdit" @refreshLabelList="getLabelList"></label-edit>
  </div>
</template>

<script>
  import AddOrUpdate from './file-add-or-update'
  import FileUpload from './file-upload.vue'
  import LabelAdd from './label-add.vue'
  import LabelEdit from './label-edit.vue'
  import Vue from 'vue'
  export default {
    components: {
      AddOrUpdate,
      FileUpload,
      LabelAdd,
      LabelEdit
    },
    data () {
      return {
        tabPosition: 'left',
        dataForm: {
          key: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        labelIdList: [],
        tabsLabelId: '00000000000000000000000000000000',  // 绑定Tabs的name，也就是当前选中的Lable的ID
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        uploadVisible: false,
        addLabelVisible:false,
        editLabelVisible:false,
        editableTabsValue: '1',
        editableTabs: [{
          labelId: '00000000000000000000000000000000',
          labelName:'默认标签',
          isDefault:false
        }],
        tabIndex: 1
      }
    },
    activated () {
      this.getDataList()
      this.getLabelList()
    },
    methods: {
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/disk/file/list'),
          method: 'post',
          data: this.$http.adornData({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key,
            'labelIdList': this.labelIdList
          })
        }).then(({data}) => {
          if (data && data.code === 200) {
            this.dataList = data.data.records
            this.totalPage = data.data.total
            this.fileLength()
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 获取标签
      getLabelList ()  {
         this.$http({
          url: this.$http.adornUrl('/disk/label/list'),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 200) {
            this.editableTabs = data.data;
            // console.log(this.editableTabs);
          }
        })
      },
      // 标签更新后更新列表
      changeLabel (tab) {
        this.labelIdList = [this.tabsLabelId]
        // this.labelIdList.push(this.tabsLabelId)
        this.getDataList()
      },
      // 文件大小转换
      fileLength(){
        // console.log(this.dataList);
        for(let i = 0;i<this.dataList.length;i++){
          // console.log(this.dataList[i].length)
          let val = this.dataList[i].length;
          let temp = Math.floor(Math.log(val) / Math.log(2));
          let list = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
          if (temp < 1) temp = 0;
          var num = Math.floor(temp / 10);
          val = val / Math.pow(2, 10 * num);
          if (val.toString().length > val.toFixed(2).toString().length) val = val.toFixed(2);
          this.dataList[i].length = val + " " + list[num];
        }
      
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 上传
      uploadFile () {
        this.uploadVisible = true
        this.$nextTick(() => {
          this.$refs.fileUpload.init()
        })
      },
      // 下载
      downloadFile (id) {
        // 获取Token
        console.log(id);
        let token = Vue.cookie.get('Auth-Token')
        let fileServerHost = ''
        let aTag = document.createElement('a')
        aTag.href = `http://localhost:7001/api/disk/file/download?fileId=${id}&Auth-Token=${token}`
        aTag.click()
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.fileId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/disk/file/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 新增标签
      addTab(){
        this.addLabelVisible = true
        this.$nextTick(() => {
          this.$refs.labelAdd.init()
        })
      },
      // 编辑标签
      editTab(){
        this.editLabelVisible = true
        this.$nextTick(()=>{
          this.$refs.labelEdit.init()
        })
      }
    }
  }
</script>
